package stark.app.function.weather;

import android.Manifest;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.weather.lib.WeatherManager;
import com.stark.weather.lib.model.bean.DbWeatherCity;
import com.stark.weather.lib.model.db.CityDbHelper;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import stark.app.R;
import stark.app.databinding.ActivityWeatherDemoBinding;
import stark.common.apis.base.Weather;
import stark.common.apis.base.WeatherLivingIndex;
import stark.common.base.IReqRetCallback;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.utils.LocationUtil;

/**
 * Author：daizhongbin on 2022/5/14
 * Email：1027154338@qq.com
 * Desc:
 */
public class WeatherDemoActivity extends BaseNoModelActivity<ActivityWeatherDemoBinding> {

    StringBuilder mStringBuilder;

    @Override
    protected int onCreate() {
        return R.layout.activity_weather_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.btnMap.setOnClickListener(v -> {
            getWeatherByMap();
        });
        mDataBinding.btnProvince.setOnClickListener(v -> {
            getProvince();
        });
        mDataBinding.btnCityByProvince.setOnClickListener(v -> {
            getCityByProvince();
        });
        mDataBinding.btnDistrictByCity.setOnClickListener(v -> {
            getDistrictByCity();
        });
    }

    @Override
    protected void initData() {
        showDialog("初始化中...");
        WeatherManager.initCityData(new WeatherManager.IInitCallback() {
            @Override
            public void onRet(boolean success) {
                dismissDialog();
                ToastUtils.showShort(success ? "初始化成功" : "初始化失败");

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopLoc();
    }

    private void getProvince() {
        //下面该方法是需要WeatherManager.initCityData初始化成功后才能获取到数据
        List<DbWeatherCity> cityList = CityDbHelper.getProvinces();
        if (cityList != null) {
            Log.e("dzb", "list = " + GsonUtils.toJson(cityList));
        }
    }

    private void getCityByProvince() {
        //下面该方法是需要WeatherManager.initCityData初始化成功后才能获取到数据
        List<DbWeatherCity> cityList = CityDbHelper.getCityInProvince("湖南");
        if (cityList != null) {
            Log.e("dzb", "list = " + GsonUtils.toJson(cityList));
        }
    }

    private void getDistrictByCity() {
        //下面该方法是需要WeatherManager.initCityData初始化成功后才能获取到数据
        List<DbWeatherCity> cityList = CityDbHelper.getDistrictInCity("长沙");
        if (cityList != null) {
            Log.e("dzb", "list = " + GsonUtils.toJson(cityList));
        }
    }

    private void getWeatherByMap() {
        boolean isEnabled = LocationUtil.isLocationEnabled();
        if (!isEnabled) {
            ToastUtils.showShort("请先打开位置服务开关");
            return;
        }
        PermissionUtils.permission(Manifest.permission.ACCESS_FINE_LOCATION)
                .callback(new PermissionUtils.SingleCallback() {
                    @Override
                    public void callback(boolean isAllGranted, @NonNull List<String> granted, @NonNull List<String> deniedForever, @NonNull List<String> denied) {
                        if (!isAllGranted) {
                            ToastUtils.showShort("请先授予位置权限");
                            return;
                        }
                        startLoc();
                    }
                })
                .request();
    }

    private AMapLocationClient mLocClient;

    private void startLoc() {
        if (mLocClient != null) {
            return;
        }
        AMapLocationClient client = new AMapLocationClient(this);
        mLocClient = client;
        AMapLocationClientOption clientOption = new AMapLocationClientOption();
        clientOption.setInterval(60 * 60 * 1000);   //每小时刷新一次
        clientOption.setNeedAddress(true);
        clientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        client.setLocationOption(clientOption);
        client.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation == null) return;
                int errCode = aMapLocation.getErrorCode();
                if (errCode != 0) return;
                double lat = aMapLocation.getLatitude();
                double lon = aMapLocation.getLongitude();

                String city = aMapLocation.getCity();//城市信息
                String district = aMapLocation.getDistrict();//城区信息

                //根据城市名称来获取天气信息
                getWeather(city);

                //根据该城市所在的更细的地址区来获取天气信息
                //getWeather(district);
            }
        });
        client.startLocation();
    }

    private void stopLoc() {
        if (mLocClient != null) {
            mLocClient.stopLocation();
            mLocClient.onDestroy();
            mLocClient = null;
        }
    }

    private void getWeather(String city) {
        mStringBuilder = new StringBuilder();
        WeatherManager.getWeather(WeatherDemoActivity.this, city, new IReqRetCallback<Weather>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable Weather result) {
                if (result != null) {
                    mStringBuilder.append("当地天气信息：\n");
                    mStringBuilder.append(result.toString() + "\n\n");
                    mDataBinding.tvContent.setText(mStringBuilder.toString());

                    mDataBinding.trendView.setTemps(result.getLowTemps(), result.getHighTemps());
                }
                getWeatherLivingIndex(city);
            }
        });
    }

    private void getWeatherLivingIndex(String city) {
        WeatherManager.getWeatherLivingIndex(WeatherDemoActivity.this, city, new IReqRetCallback<WeatherLivingIndex>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable WeatherLivingIndex result) {
                if (result != null) {
                    mStringBuilder.append("当地天气生活指数：\n");
                    mStringBuilder.append(result.toString() + "\n");
                    mDataBinding.tvContent.setText(mStringBuilder.toString());
                }

            }
        });
    }
}
